package com.itany.book.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.book.exception.UserPhoneExistsException;
import com.itany.book.pojo.Address;
import com.itany.book.user.service.IUserService;
import com.itany.book.user.dao.UserMapper;
import com.itany.book.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by tyh on 2018/9/22.
 */
@Service
@com.alibaba.dubbo.config.annotation.Service
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void addUser(User user) {
        // user.setCreateDate(new Date());
        userMapper.addUser(user);
        System.out.println(1/0);
    }


    @Override
    public PageInfo<User> findUsers(Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        List<User> list =  userMapper.findUserAll();
        PageInfo<User> pageInfo = new PageInfo<User>(list);
        return pageInfo;
    }

    @Override
    public User login(User user) {
        return userMapper.login(user);
    }

    @Override
    public User register(User user) throws UserPhoneExistsException {
        // 根据手机查找用户
        String phone = user.getPhone();
        User u = userMapper.selectByPhone(phone);
        if (u != null){
            throw new UserPhoneExistsException("用户手机号已注册！");
        }
        userMapper.addUser(user);
        return u;
    }
    @Override
    public List<Address> findAllAddress(String username) {
        return userMapper.findAllAddress(username);
    }

    @Override
    public User selectByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
}
